package com.example.finaldemo;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GPT {
    private OkHttpClient client;
    private MediaType mediaType;
    private ArrayList<String> conversationHistory;

    private String GPTKey="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";

    public GPT(){
        ProxySelector proxySelector = new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                List<Proxy> proxyList = new ArrayList<>();
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                proxyList.add(proxy);
                return proxyList;
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                System.out.println("代理超时");
            }
        };
        client = new OkHttpClient().newBuilder()
                .proxySelector(proxySelector)   //设置本机代理
                .connectTimeout(60, TimeUnit.SECONDS)   // 设置连接超时时间为20秒
                .readTimeout(60, TimeUnit.SECONDS)      // 设置读取超时时间为20秒
                .build();
        mediaType = MediaType.parse("application/json");
        conversationHistory = new ArrayList<>();
    }

    public GPT(String GPTKey){

        this.GPTKey = GPTKey;

        ProxySelector proxySelector = new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                List<Proxy> proxyList = new ArrayList<>();
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                proxyList.add(proxy);
                return proxyList;
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                System.out.println("代理超时");
            }
        };
        client = new OkHttpClient().newBuilder()
                .proxySelector(proxySelector)   //设置本机代理
                .connectTimeout(60, TimeUnit.SECONDS)   // 设置连接超时时间为20秒
                .readTimeout(60, TimeUnit.SECONDS)      // 设置读取超时时间为20秒
                .build();
        mediaType = MediaType.parse("application/json");
        conversationHistory = new ArrayList<>();
    }

    public String answer(String question) {

        try {
            conversationHistory.add(question); // 将当前问题加入对话历史

            // 构建历史对话内容
            StringBuilder messageBuilder = new StringBuilder();
            for (String message : conversationHistory) {
                messageBuilder.append("{\"role\": \"user\", \"content\": \"").append(message).append("\"},");
            }
            String messages = messageBuilder.toString();

            RequestBody body = RequestBody.create(mediaType, "{\n" +
                    "    \"model\": \"gpt-3.5-turbo-16k\",\n" +
                    "    \"messages\": [\n" +
                    "        " + messages + "\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}");

            Request request = new Request.Builder()
                    .url("https://api.openai.com/v1/chat/completions")
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer " + GPTKey)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            System.out.println(responseBody);

            // 解析响应并获取内容
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseJson = objectMapper.readTree(responseBody);
            JsonNode choicesNode = responseJson.get("choices");
            if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                JsonNode messageNode = choicesNode.get(0).get("message");
                if (messageNode != null && messageNode.isObject()) {
                    JsonNode contentNode = messageNode.get("content");
                    if (contentNode != null && contentNode.isTextual()) {
                        String content = contentNode.asText();

                        System.out.println(content);

                        return content;
                    }
                }
            }

            return responseBody;

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
            return e.toString();
        } catch (NullPointerException e){
            e.printStackTrace();
            return e.toString();
        }
    }


    public static void main(String[] args) throws IOException {
        GPT gpt = new GPT();
        gpt.answer("你好");
    }
}
